<template>
  <PageWrapDrawer :show="show" :isUpdate="isUpdate" 
  @success="onSubmit" 
  @on-drawer-close="onClose">
    <Form name="basic"
          :model="insideData.data"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
          autocomplete="off"
          layout="horizontal"
    >
      <FormItem label="内部名称" name="name" v-bind="validateInfos['data.name']">
        <a-input v-model:value="insideData.data.name"/>
      </FormItem>

      <FormItem label="路径" name="path" v-bind="validateInfos['data.path']">
        <a-input v-model:value="insideData.data.path"/>
      </FormItem>

      <FormItem label="组件" name="component" v-bind="validateInfos['data.component']">
        <a-input v-model:value="insideData.data.component"/>
      </FormItem>
      <FormItem label="重定向" name="redirect">
        <a-input v-model:value="insideData.data.redirect"/>
      </FormItem>
      <FormItem label="父ID" name="parentId">
        <InputNumber v-model:value="insideData.data.parentId" :min="0" style="width: 200px;"
        :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
        :parser="value => value.replace(/\$\s?|(,*)/g, '')"/>
      </FormItem>
      <FormItem label="顺序" name="sort">
        <InputNumber v-model:value="insideData.data.sort" :min="0" :max="9999"/>
      </FormItem>
      <FormItem label="按钮" name="buttonList">
        <Select v-model:value="insideData.data.bidList" mode="tags" allowClear placeholder="请选择"
        :options="selectedOptionsButtonList"/>
      </FormItem>

      <Divider orientation="left">元信息</Divider>
      <FormItem label="标题" name="title" v-bind="validateInfos['data.meta.title']">
        <a-input v-model:value="insideData.data.meta.title"/>
      </FormItem>
      <FormItem label="图标" name="icon">
        <a-input v-model:value="insideData.data.meta.icon"/>
      </FormItem>
      <FormItem label="顺序" name="orderNo">
        <InputNumber v-model:value="insideData.data.meta.orderNo" :min="0" :max="999"/>
      </FormItem>
      <FormItem label="菜单" name="hideMenu">
        <RadioGroup v-model:value="insideData.data.meta.hideMenu">
          <Radio :value="false">显示</Radio>
          <Radio :value="true">隐藏</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="面包屑" name="hideChildrenInMenu">
        <RadioGroup v-model:value="insideData.data.meta.hideChildrenInMenu">
          <Radio :value="false">显示</Radio>
          <Radio :value="true">隐藏</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="Tab图钉" name="affix">
        <RadioGroup v-model:value="insideData.data.meta.affix">
          <Radio :value="true">固定</Radio>
          <Radio :value="false">不固定</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="Tab" name="affix">
        <RadioGroup v-model:value="insideData.data.meta.hideTab">
          <Radio :value="false">显示</Radio>
          <Radio :value="true">隐藏</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="链接" name="isLink">
        <RadioGroup v-model:value="insideData.data.meta.isLink">
          <Radio :value="true">是</Radio>
          <Radio :value="false">否</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="Iframe" name="frameSrc">
        <a-input v-model:value="insideData.data.meta.frameSrc"/>
      </FormItem>
    </Form>
  </PageWrapDrawer>
</template>
<script lang="ts" name="menuDrawer" setup>
import {ref, reactive, toRaw, watchPostEffect} from 'vue';
import {useMessage} from '/@/hooks/web/useMessage';
import {PageWrapDrawer} from '/@/components/PageWrapDrawer'
import {create, update} from '/@/api/admin/menu';
import {getListData} from '/@/api/admin/button';
import {
  Form,
  FormItem,
  InputNumber,
  Radio, RadioGroup,
  Divider,
  Select, SelectProps,
} from 'ant-design-vue';
import {groupBy} from 'lodash-es'

// https://blog.csdn.net/qq_49327308/article/details/124467691
const {
      createMessage,
    } = useMessage();
    const {info, success, warning, error} = createMessage;

const emit = defineEmits(['on-success', 'on-drawer-close'])
const props = defineProps({
    show: Boolean,
    isUpdate: Boolean,
    row: {type: [Object, null] as PropType<Object | null>, default: null,},
})

const useForm = Form.useForm;
const insideData = reactive({
  data: {
    id: null,
    name: '',
    path: '',
    component: '',
    redirect: '',
    parentId: 0,
    metaId: 0,
    sort: 0,
    buttonList: [],
    bidList: [], // 新增和更新时，存放按钮ID的辅助字段
    meta: {
      title: '',
      icon: '',
      orderNo: 0,
      hideMenu: false,
      hideChildrenInMenu: false,
      affix: false,
      hideTab: false,
      isLink: false,
      frameSrc: '',
    },
  }
});

// const selectedButtonList = ref([]);
const selectedOptionsButtonList = ref<SelectProps['options']>([]);

watchPostEffect(() => {
  let v1 = props.row as any
  if (v1) {
    insideData.data = {...v1}
    insideData.data.bidList = v1.buttonList && v1.buttonList.map((e:any) => e.id) || []
  }
  if (props.show) {
    getListData().then(d => {
      // selectedOptionsButtonList.value = d.map(e => {
      //   return {label: e.name, value: e.id}
      // })
      let list = d.map((e:any) => {
        let group = ''
        switch (e?.place) {
          case 0: group = '表格上方-左边'; break;
          case 1: group = '表格上方-右边'; break;
          case 2: group = '表格内-操作';break;
          case 3: group = '其他'; break;
        }
        return {label: e.name, value: e.id, group: group}
      })
      let groupby = groupBy(list, 'group')
      let newArr = [] as any[]
      Object.keys(groupby).forEach(key => newArr.push({label: key, options: groupby[key] }))
      // console.log(newArr, groupby)
      selectedOptionsButtonList.value = newArr
    })
  }
})

const rulesRef = reactive({
  'data.name': [
    {required: true, message: '请输入内部名称',},
  ],
  'data.path': [
    {required: true, message: '请输入路径',},
  ],
  'data.component': [
    {required: true, message: '请输入组件',},
  ],
  'data.meta.title': [
    {required: true, message: '请输入标题'}
  ]
});
const {resetFields, validate, validateInfos} = useForm(insideData, rulesRef, {
  onValidate: (...args) => {
    // console.log('args=>', ...args)
  },
});

const onSubmit = () => {
  validate()
    .then(async () => {
      let data = toRaw(insideData.data)
      if (props.isUpdate) {
        await update(data).then(() => {
          onClose()
          // success({content: dd.msg})
        })
      } else {
        await create(data).then(() => {
          onClose()
          // success({content: dd.msg})
        })
      }
      emit('on-success')
    }).catch(err => {
    console.log('error-----', err);
  });
}

const onClose = () => {
  Object.assign(insideData, {data: {meta: {}}});
  resetFields();
  emit('on-drawer-close');
};

</script>
